import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import '../constants/app_colors.dart';
import '../models/thought_record.dart';
import 'thought_reshaping_screen.dart';
import 'package:heroicons/heroicons.dart';

class ThoughtDetailScreen extends StatelessWidget {
  final ThoughtRecord thoughtRecord;

  const ThoughtDetailScreen({
    Key? key,
    required this.thoughtRecord,
  }) : super(key: key);

  // 定义标签颜色映射为静态常量
  static final Map<String, Color?> labelColors = {
    '非黑即白': Colors.red[300],
    '以偏概全': Colors.blue[300],
    '心理过滤': Colors.green[300],
    '否定正面思维': Colors.purple[300],
    '跳跃式结论': Colors.orange[300],
    '情绪化推理': Colors.teal[300],
    '应该陈述': Colors.pink[300],
    '贴标签': Colors.indigo[300],
    '个人化': Colors.amber[300],
    '放大与缩小': Colors.cyan[300],
  };

  Widget _buildSection({
    required String title, 
    required String content,
    required Widget icon,  // 修改为 Widget 类型
    Color? iconColor = Colors.grey,  // 保持颜色参数
  }) {
    String formattedContent = content;
    if (title == '行动计划' && content.isNotEmpty) {
      formattedContent = content.replaceAll('。', '。\n');
    }

    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(
          color: Colors.grey.withOpacity(0.2),
          width: 1,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              if (icon != null) ...[
                icon,  // 直接使用传入的 widget
                const SizedBox(width: 8),
              ],
              Text(
                title,
                style: GoogleFonts.zcoolKuaiLe(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          Text(
            formattedContent,
            style: GoogleFonts.zcoolKuaiLe(
              fontSize: 18,
              color: AppColors.textPrimary,
              height: 1.5,
            ),
          ),
          if (title == '消极想法' && thoughtRecord.distortionLabels.isNotEmpty) ...[
            const SizedBox(height: 16),
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: thoughtRecord.distortionLabels.map((label) {
                final color = labelColors[label] ?? Colors.grey[300];
                return Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    color: color?.withOpacity(0.2),
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(
                      color: color ?? Colors.grey,
                      width: 1,
                    ),
                  ),
                  child: Text(
                    label,
                    style: GoogleFonts.zcoolKuaiLe(
                      fontSize: 14,
                      color: color?.withOpacity(0.8),
                    ),
                  ),
                );
              }).toList(),
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildHistoryItem({required String question, required String answer}) {
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(
          color: Colors.grey.withOpacity(0.2),
          width: 1,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                width: 24,
                height: 24,
                decoration: BoxDecoration(
                  color: AppColors.primary.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Center(
                  child: Text(
                    'Q',
                    style: GoogleFonts.zcoolKuaiLe(
                      color: AppColors.primary,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: Text(
                  question,
                  style: GoogleFonts.zcoolKuaiLe(
                    fontSize: 16,
                    color: AppColors.textPrimary,
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                width: 24,
                height: 24,
                decoration: BoxDecoration(
                  color: Colors.green.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Center(
                  child: Text(
                    'A',
                    style: GoogleFonts.zcoolKuaiLe(
                      color: Colors.green,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: Text(
                  answer,
                  style: GoogleFonts.zcoolKuaiLe(
                    fontSize: 16,
                    color: AppColors.textPrimary,
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  List<Widget> _buildReflectionHistory() {
    if (thoughtRecord.reflectionAnswers == null ||
        thoughtRecord.reflectionAnswers!.isEmpty) {
      print('No reflection answers found');
      return [];
    }

    print('Reflection answers: ${thoughtRecord.reflectionAnswers}');
    final answers = thoughtRecord.reflectionAnswers!;
    final result = <Widget>[];

    // 每两个元素构成一个问答对
    for (int i = 0; i < answers.length; i += 2) {
      if (i + 1 < answers.length) {
        print('Processing QA pair:');
        print('Question: ${answers[i]}');
        print('Answer: ${answers[i + 1]}');
        result.add(_buildHistoryItem(
          question: answers[i],
          answer: answers[i + 1],
        ));
      }
    }

    return result;
  }

  @override
  Widget build(BuildContext context) {
    print('Building detail screen with thought record:');
    print('Thought: ${thoughtRecord.thought}');
    print('Balanced View: ${thoughtRecord.balancedView}');
    print('Action Plan: ${thoughtRecord.actionPlan}');
    print('Reflection Answers: ${thoughtRecord.reflectionAnswers}');
    print('Positive Thought: ${thoughtRecord.positiveThought}');

    return Scaffold(
      backgroundColor: Colors.grey[50],
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        title: Text(
          '想法详情',
          style: GoogleFonts.zcoolKuaiLe(
            fontSize: 20,
            fontWeight: FontWeight.bold,
          ),
        ),
        centerTitle: true,
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: AppColors.textPrimary),
          onPressed: () {
            Navigator.pushReplacement(
              context,
              MaterialPageRoute(
                builder: (context) => const ThoughtReshapingScreen(),
              ),
            );
          },
        ),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(24),
        child: Column(
          children: [
            _buildSection(
              title: '消极想法', 
              content: thoughtRecord.thought,
              icon: HeroIcon(
                HeroIcons.cloud,
                style: HeroIconStyle.solid,
                size: 24,
                color: Colors.blueGrey,
              ),
            ),
            const SizedBox(height: 16),
            ..._buildReflectionHistory(),
            const SizedBox(height: 16),
            if (thoughtRecord.positiveThought != null && thoughtRecord.positiveThought!.isNotEmpty) ...[
              _buildSection(
                title: '积极想法',
                content: thoughtRecord.positiveThought!,
                icon: HeroIcon(
                  HeroIcons.lightBulb,
                  style: HeroIconStyle.solid,
                  size: 24,
                  color: Colors.yellow[700],
                ),
              ),
              const SizedBox(height: 16),
            ],
            if (thoughtRecord.balancedView != null && thoughtRecord.balancedView!.isNotEmpty) ...[
              _buildSection(
                title: '平衡观点', 
                content: thoughtRecord.balancedView!,
                icon: HeroIcon(
                  HeroIcons.scale,
                  style: HeroIconStyle.solid,
                  size: 24,
                  color: Colors.amber[700],
                ),
              ),
              const SizedBox(height: 16),
            ],
            if (thoughtRecord.actionPlan != null && thoughtRecord.actionPlan!.isNotEmpty) ...[
              _buildSection(
                title: '行动计划', 
                content: thoughtRecord.actionPlan!,
                icon: HeroIcon(
                  HeroIcons.arrowTrendingUp,
                  style: HeroIconStyle.solid,
                  size: 24,
                  color: Colors.purple[400],
                ),
              ),
              const SizedBox(height: 16),
            ],
          ],
        ),
      ),
    );
  }
} 